﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace FileManagement
{
    public partial class Form1 : Form
    {
        private OpenFileDialog openFileDialog1;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.openFileDialog1 = new OpenFileDialog();
            this.SuspendLayout();

            // button_file
            this.button_file.Name = "button_file";
            this.button_file.TabIndex = 0;
            this.button_file.Text = "选择C#源文件";
            this.button_file.UseVisualStyleBackColor = true;
            this.button_file.Click += new System.EventHandler(this.button_file_Click);
          
            // label1
            this.label1.AutoSize = true;

            this.label1.Name = "label1";
    
            this.label1.TabIndex = 1;
            this.label1.Text = "";
            
            // label2
            this.label2.AutoSize = true;

            this.label2.Name = "label2";

            this.label2.TabIndex = 2;
            this.label2.Text = "";
            
            // dataGridView2
            this.dataGridView2.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
         
            this.dataGridView2.Name = "dataGridView2";
            this.dataGridView2.TabIndex = 3;
          
            // MainForm
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = AutoScaleMode.Font;
           
            this.Controls.Add(this.dataGridView2);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.button_file);
            this.Name = "MainForm";
            this.StartPosition = FormStartPosition.CenterScreen;
            this.Text = "C#源文件格式化与统计";
            this.ResumeLayout(false);
            this.PerformLayout();
        }
        private void button_file_Click(object sender, EventArgs e)
        {
            openFileDialog1.Filter = "C#源文件 (*.cs)|*.cs";
            openFileDialog1.Multiselect = false;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                var fileName = openFileDialog1.FileName;
                ProcessFile(fileName);
            }
        }

        private void ProcessFile(string fileName)
        {
            string[] lines = File.ReadAllLines(fileName);

            var originalLineCount = lines.Length;
            var originalContent = File.ReadAllText(fileName);
            var originalWordCount = CalculateWordCount(originalContent);

            label1.Text = $"原始行数：{originalLineCount}, 单词数：{originalWordCount}";

            string[] cleanedLines = CleanFileContent(lines);
            string cleanedContent = string.Join(Environment.NewLine, cleanedLines);

            var cleanedLineCount = cleanedLines.Length;
            var cleanedWordCount = CalculateWordCount(cleanedContent);

            label2.Text = $"格式化后行数：{cleanedLineCount}, 单词数：{cleanedWordCount}";

            var wordFrequency = CalculateWordFrequency(cleanedContent);

            dataGridView2.DataSource = wordFrequency;

            dataGridView2.AutoResizeColumns();
            dataGridView2.Columns[0].HeaderText = "单词";
            dataGridView2.Columns[1].HeaderText = "出现频率";
        }

        private int CalculateWordCount(string content)
        {
            char[] delimiters = new char[] { ' ', '\r', '\n', '\t', ',', '.', ':', ';', '(', ')', '[', ']', '{', '}', '<', '>', '|', '\\', '/', '\"', '\'', '@', '+', '=', '*', '&', '^', '%', '$', '#', '!', '~', '`', '?', '-' };
            var words = content.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
            return words.Length;
        }

        private string[] CleanFileContent(string[] lines)
        {
            var cleanedLines = lines.Where(line => !line.TrimStart().StartsWith("//") && !string.IsNullOrWhiteSpace(line)).ToArray();
            return cleanedLines;
        }

        private List<WordFrequency> CalculateWordFrequency(string content)
        {
            char[] delimiters = new char[] { ' ', '\r', '\n', '\t', ',', '.', ':', ';', '(', ')', '[', ']', '{', '}', '<', '>', '|', '\\', '/', '\"', '\'', '@', '+', '=', '*', '&', '^', '%', '$', '#', '!', '~', '`', '?', '-' };

            var matches = content.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);

            var grouped = matches.GroupBy(word => word).Select(g => new WordFrequency { Word = g.Key, Frequency = g.Count() });

            return grouped.OrderBy(x => x.Word).ToList();
        }

        private void button1_Click(object sender, EventArgs e)
        {

        }
    }
    public class WordFrequency
    {
        public string Word { get; set; }
        public int Frequency { get; set; }
    }
}
